<template>
  <div class="wfull">
    <el-cascader
      :placeholder="$t('storeManagement_businessCategory_placeholder')"
      v-model="localModelValue"
      class="wfull"
      :options="formattedOptions"
      :props="cascaderProps"
      collapse-tags
      collapse-tags-tooltip
      :max-collapse-tags="1"
      clearable
      @change="handleChange"
      filterable
      :disabled="disabled"
    />
  </div>
</template>

<script lang="ts">
// 经营类目下拉列表组件
import { ref, watch, defineComponent, toRefs } from "vue";
import { getIndustry } from "@/service/clueInformation/clueInformation";
export default defineComponent({
  props: {
    modelValue: {
      type: Array as () => string[][],
      default: () => [],
    },
    disabled: {
      type: Boolean,
      default: () => false
    }

  },
  emits: ["update:modelValue", "getLabels"], // 声明组件将发出的事件
  setup(props, { emit }) {
    // 使用 toRefs 将 props 中的响应式属性转换为独立的响应式引用
    const { modelValue } = toRefs(props);
    const cascaderProps = ref({
      multiple: true,
      expandTrigger: "hover" as const,
      value: "industryId",
      label: "industryName",
    });
    const localModelValue = ref<string[][]>([]);
    const options = ref([]);

    function findLabelByPath(path:string[], options:any):any {
      if (path.length === 0 || !options) return [];
      
      const value = path[0];
      const option = options.find((o:any) => o.industryId === value);
      if (!option) return [];

      // 如果是最后一个值，直接返回当前label
      if (path.length === 1) {
        return [option.industryName];
      }

      // 递归处理子路径
      return [option.industryName].concat(
        findLabelByPath(path.slice(1), option.children)
      );
    }

    const getLabels = (
      options: string[][],
      selectedValues: string[][]
    ) => {
      if (!selectedValues.length) {
        return;
      }
      let labelsList:string[][] = selectedValues.map(path => findLabelByPath(path, options))??[];
      let labelStrList:string[] = []
      labelStrList = labelsList.map((item) => item.join("/"))
      return labelStrList;
    };

    // 递归格式化 options 中的 value 为字符串
    function formatOptions(options: any[]): any[] {
      return options.map((option) => ({
        ...option,
        industryId: String(option.industryId),
        industryOrder: String(option.industryOrder),
        level: String(option.level),
        parenId: String(option.parenId),
        children: option.children ? formatOptions(option.children) : [],
      }));
    }
    // 格式化 options，确保 value 是字符串类型
    const formattedOptions = ref<string[][]>([]);
    getIndustry().then((res) => {
      if (res && res.data && res.data.data) {
        options.value = res.data.data;
        formattedOptions.value = formatOptions(options.value);
      }
    }).catch((err) =>{
      console.log(err);
      
    });

    const handleChange = () => {
      let len = localModelValue.value.length;
      if (len > 5) {
        let tempList:string[][] = []
        for (let i = 0; i < localModelValue.value.length; i++) {
          if (i < 5) {
            tempList.push(localModelValue.value[i])
          }else{
            break
          }
        }
        localModelValue.value = tempList
      }
    };

    // 监听父组件传递的 modelValue 的变化
    watch(
      modelValue,
      (newVal: string[][]) => {
        // 当父组件更新 modelValue 时，同步更新本地状态
        localModelValue.value = newVal;
      },
      {
        immediate: true,
        deep: true,
      }
    );

    // 监听本地状态的变化，并通知父组件
    watch(localModelValue, (newVal) => {
      // 触发自定义事件，将新的值传递给父组件

      let label: string[] = [];
      label = getLabels(formattedOptions.value, newVal) ?? [];
      emit("getLabels", label);
      emit("update:modelValue", newVal);
    });
    return {
      cascaderProps,
      localModelValue,
      formattedOptions,
      handleChange,
    };
  },
});
</script>
